import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login.vue'
// import register from '@/views/register.vue'
// import detail from '@/views/detail.vue'
import layout from '../views/layout.vue'
// import like from '@/views/like.vue'
// import collect from '@/views/collect.vue'
// import user from '@/views/user.vue'
// import article from '@/views/article.vue'
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: layout,
    redirect: '/article',
    children: [
      { path: '/like', component: () => import('@/views/like.vue') },
      { path: '/collect', component: () => import('@/views/collect.vue') },
      { path: '/user', component: () => import('@/views/user.vue') },
      { path: '/article', component: () => import('@/views/article.vue') }
    ]
  },
  { path: '/login', component: login },
  { path: '/register', component: () => import('@/views/register.vue') },
  { path: '/detail/:id', component: () => import('@/views/detail.vue') }

]

const router = new VueRouter({
  routes
})

// 注册全局前置守卫
// 一旦注册了 全局前置守卫 那守卫就生效了 所有页面的跳转由守卫放行
// router.beforeEach
// to from next 函数决定哪个是否放行
// next （）表示放行 next （false）不放行 调用next （'路径'） 指定跳转
router.beforeEach((to, from, next) => {
  // console.log(to, from)
  // to 到哪去 from 从哪里来
  // console.log(to.path, from.path)
  // next()
  const token = getToken()
  if (token) {
    next()
  } else {
  // 判断是否在白名单
    const whiteList = ['/register', '/login']
    // if (to.path==='/register' || to.path==='/login') {

    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      Toast.fail('您还没登录呢，请登录')
    }
  }
})

export default router
